package com.testes.umov.sync;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;

import com.testes.umov.util.testesUtils;



import android.util.Log;


public class HttpConnector {

	private static final int RESPONSE_CODE_TIMEOUT = 999;
	private static final int RESPONSE_CODE_EXCEPTION = 0;
	private static final int MAX_CONNECTION_RETENTIVE_BY_TIMEOUT = 3;
	private String contentType;
	
	@SuppressWarnings("finally")
	public boolean doConnection(final byte[] dataToSend, int retentiveNumberByTimeout, int retentiveNumberByTimeout2, final boolean dataCompressionEnable) {

		// updateAddressRetentiveDateAndHour(address, retentiveNumberByTimeout);
		boolean result = true;
		HttpURLConnection connection = null;
		String address = "";
		
		try {

			address = "http://sync.umov.me:80/trevisan/uMovServer/uMovServer.exe/50?";
			address += "agelogin=master.testeios15&agesen=senha&pdvcod=-1&ver=03.73&verdic=42&dth="; 
			address += testesUtils.getCurrentTime();
			address += "&stat=2&verbas=426307154&size=20000&sinccounter=1&app=mob&platform=android&compacta=N&pacote=1";
			URL url = new URL(address);
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoInput(true);
			setTimeOutConnection(connection, 100000);
			System.out.println("===============\nSending data!");
			sendData(connection, dataToSend, 100000);

			int responseCode = connection.getResponseCode();

			if (responseCode == HttpURLConnection.HTTP_OK) {
				System.out.println("===============\nHTTP OK");
			} else {
				System.out.println("===============\nHTTP FAIL");
				result = false;
			}

		} catch (SocketTimeoutException se) {

			/*if (!isFirstPackage(address) && retentiveNumberByTimeout < MAX_CONNECTION_RETENTIVE_BY_TIMEOUT) {
				retentiveNumberByTimeout++;
				closeConnection(connection);
				waitForNewConnection();
				return doConnection(dataToSend, 999, retentiveNumberByTimeout, dataCompressionEnable);

			} else {
				result = false;
			}*/
			System.out.println("===============\nTimeout!");

		} catch (Exception ex) {

			

		} 
		finally {
			closeConnection(connection);
			return result;
		}

	}
	
	private boolean isFirstPackage(final String address) {
		return address.endsWith("=1");
	}
	
	private void waitForNewConnection() {
		try {
			Thread.sleep(3000);
		} catch (Exception e) {
		}
	}
	
	private void closeConnection(HttpURLConnection connection) {
		if (connection != null) {
			connection.disconnect();
		}
	}
	
	private void setTimeOutConnection(HttpURLConnection connection, int timeOutConnection) {
		if (timeOutConnection > 0) {
			connection.setConnectTimeout(timeOutConnection);
			connection.setReadTimeout(timeOutConnection * 2);
		}
	}

	private void sendData(HttpURLConnection connection, byte[] dataToSend, int timeOutConnection) throws SocketTimeoutException, Exception {
		if (dataToSend != null && dataToSend.length > 0) {
			
			TimeOutController timeOutController = new TimeOutController(timeOutConnection/1000);
			
			if(timeOutConnection > 0){
				timeOutController.start();
			}
			
			OutputStream outputStream = null;
			
			try {
				System.out.println("1");
				connection.setRequestMethod("POST");
				connection.setDoOutput(true);
				System.out.println("2");
				if (contentType != null) {
					connection.setRequestProperty("Content-Type", contentType);
				}
				System.out.println("3");
				connection.setFixedLengthStreamingMode(dataToSend.length);
				System.out.println("4");
				outputStream = new BufferedOutputStream(connection.getOutputStream(), dataToSend.length);
				System.out.println("5");
				for (int i = 0; i < dataToSend.length; i++) {
					outputStream.write(dataToSend[i]);
					
					if(timeOutController.wasTimeOutExceeded()){
						throw new SocketTimeoutException();
					}
				}
				System.out.println("6");
				outputStream.flush();
				System.out.println("7");
			}
			catch(Exception e) {
				System.out.println("7 - Fuuuuuuuu");
			}
			finally {
				if(timeOutController != null){
					System.out.println("8");
					timeOutController.stop();
					System.out.println("9");
				}

				try{
					System.out.println("10");
					if (outputStream != null){
						outputStream.close();
					}
					System.out.println("11");
				}
				catch(IOException e)
				{
					System.out.println("11 - Fuuuuuuuu");
				}
			}
		} else {
			System.out.println("12");
			connection.setRequestMethod("GET");
			System.out.println("13");
		}
	}	
	
}
